//
//  HDAddressObject.m
//  Food
//
//  Created by admin on 2018/8/10.
//  Copyright © 2018年 包月兴. All rights reserved.
//

#import "HDAddressObject.h"
#import <BmobSDK/Bmob.h>
#import "RLMObject+Extension.h"
@implementation HDAddressObject
+(NSString *)primaryKey
{
    return @"objectId";
}

+(void)insertDataWithBmobObjectLists:(NSArray<BmobObject *> *)lists complete:(void (^)(NSError * _Nullable))complete
{
       __block NSMutableArray *arr = [NSMutableArray array];
    [lists enumerateObjectsUsingBlock:^(BmobObject * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        HDAddressObject *addressObject = [[HDAddressObject alloc] initWithBmobObject:obj];
        [arr addObject:addressObject];
    }];
    if (arr.count > 0) {
        [self asynDataBlock:^{
            RLMRealm *realm = [RLMRealm defaultRealm];
            NSError *error;
            [realm transactionWithBlock:^{
                [realm addOrUpdateObjects:arr];
            } error:&error];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(error);
                }
            });
        }];
        return;
    }
    if (complete) {
        complete(nil);
    }
}


+(void)deleteAddressObjectWithObjectId:(NSString *)objectId
{
    
    [self asynDataBlock:^{
        HDAddressObject *addressObject = [HDAddressObject objectForPrimaryKey:objectId];
        RLMRealm *realm = [RLMRealm defaultRealm];
        NSError *error;
        [realm transactionWithBlock:^{
            [realm deleteObject:addressObject];
        } error:&error];
    }];
}


+(RLMResults *)listResults
{
    NSString *where = [NSString stringWithFormat:@"userObjectId = '%@'",[BmobUser currentUser].objectId];
    
    return [HDAddressObject objectsWhere:where];
}

-(instancetype)initWithBmobObject:(BmobObject *)object
{
    if (self = [super init]) {
        _objectId = [object objectForKey:@"objectId"];
        _realName = [object objectForKey:@"ralname"];
        _mobile = [object objectForKey:@"mobile"];
        _detailAddress = [object objectForKey:@"detail"];
        _userObjectId = [BmobUser currentUser].objectId;
    }
    return self;
}
@end
